//
//  ShoppingBagViewController.m
//  PeopleStreet
//
//  Created by 辰领科技 on 16/1/14.
//  Copyright © 2016年 yuf. All rights reserved.
//

#import "ShoppingBagViewController.h"
#import "ShoppingBagTableViewCell.h"
#import "AttributScroView.h"
#import "SureIndentViewController.h"
#import "ShopViewController.h"
#import "ShoppingProductDetailViewController.h"
static NSString *cellIdentify = @"ShoppingBagTableViewCell";
@interface ShoppingBagViewController ()<UITableViewDataSource,UITableViewDelegate>{
    NSInteger _totle;
}
@property (nonatomic,assign)   NSInteger    pageNO;
@property (strong, nonatomic) IBOutlet UIView *navView;
@property (strong, nonatomic) IBOutlet UIButton *headTitel;//购物袋label
@property (strong, nonatomic) IBOutlet UILabel *totalPrice;//总计label
@property(nonatomic,assign)CGFloat totalMoney;
@property(nonatomic,strong)NSMutableDictionary * choseArray;
@property(nonatomic,assign)bool delete;
@property (strong, nonatomic) IBOutlet UIButton *payButton;//结算按钮
@property (strong, nonatomic) IBOutlet UIView *payView; //结算View
@property (strong, nonatomic) IBOutlet UIView *deleteView;//删除按钮视图
@property (strong, nonatomic) IBOutlet UIButton *deleteButton;//删除按钮
@property (strong, nonatomic) IBOutlet UITableView *listTableView;
@property(nonatomic,strong)NSMutableArray * goodsArray;

@property (strong, nonatomic) IBOutlet UIView *changePropertyView;//修改款式View
@property (strong, nonatomic) IBOutlet UIButton *sureChangeButton;//确认修改按钮

@property (strong, nonatomic) IBOutlet UIView *propertyView;//款式View
@property (strong, nonatomic) IBOutlet UIImageView *propertyImage;//修改尺码图片

@property (strong, nonatomic) IBOutlet UILabel *propertyPrice;//修改尺码价格
@property (strong, nonatomic) IBOutlet UILabel *propertyNumber;//修改尺码库存

@property (strong, nonatomic) IBOutlet UILabel *typeAndSize;//修改尺码尺码
@property(nonatomic,assign)NSInteger changIndex;//编辑中的index
@property(nonatomic,assign)NSInteger changSection;//编辑中的section

@property(nonatomic,strong)NSString * size;
@property(nonatomic,strong)NSString * type;
@property (strong, nonatomic) NSMutableDictionary *perportyDic;
@property(nonatomic,strong)NSString * mgspId;
@property(nonatomic,strong)NSString * mgspPrice;
@property (strong, nonatomic) NSMutableArray *perportyOneArr;
@property (strong, nonatomic) NSMutableArray *perportyTwoArr;

@end

@implementation ShoppingBagViewController
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if ([Common getLoginStatus]) {
        [self getBagNumber];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _totalMoney = 0;
    _goodsArray = [ NSMutableArray array];
    _choseArray = [NSMutableDictionary dictionary];
    _perportyDic = [NSMutableDictionary dictionary];
    _perportyOneArr = [NSMutableArray array];
    _perportyTwoArr = [NSMutableArray array];
    _delete = NO;
    self.pageNO = 1;
//    NSDictionary * dic = @{@"shopName":@"时尚楠楠家",@"goodsImage":@"shopping6",@"infoLabel":@"马丁靴潮女短靴英伦风平底2015秋季新款短筒厚底女靴",@"numberLabel":@"1",@"propertyLabel":@"颜色分类：军绿色；尺码：35",@"priceLabel":@"99.19",@"oldPriceLabel":@"389.00"};
//    _goodsArray = [@[dic,dic,dic]mutableCopy];
    [self initViewLayOut];
    [self addRefreshing];
    
    // Do any additional setup after loading the view.
}

- (void)initViewLayOut{

    [self adaptiveViewLayout:self.view];
    [self adaptiveViewLayout:self.navView];
    [self adaptiveViewLayout:self.payView];
    [self adaptiveViewLayout:self.deleteView];
    [self adaptiveViewLayout:self.changePropertyView];
    [self adaptiveViewLayout:self.propertyView];
    self.changePropertyView.hidden = YES;
   
  
    //注册
    [self.listTableView registerClass:[ShoppingBagTableViewCell class]  forCellReuseIdentifier:cellIdentify];
    self.listTableView.separatorStyle = NO;
    
}



#pragma mark -- 添加刷新数据
- (void)addRefreshing{
    self.listTableView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        int64_t delayInSeconds = 8.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            [self.listTableView.header endRefreshing];
        });
        self.pageNO = 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getShoppingCar];
        });
    }];
    // 马上进入刷新状态
    [self.listTableView.header beginRefreshing];
}
//加载更多数据
- (void)loadMoreData{
    if (self.goodsArray.count == _totle) {
        [self.listTableView.footer endRefreshing];
    }else{
        self.pageNO = self.pageNO + 1;
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            //请求商家数据
            [self getShoppingCar];
        });
    }
    
}


#pragma mark  获取购物袋数量--=========================================
-(void)getBagNumber{
    
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic setObject:@"queryCartProductTotalNum" forKey:@"method"];
    [dic setObject:[Common getLoginInfo][@"userId"] forKey:@"userId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_queryCartProductTotalNum withHttpType:@"POST" withTag:SX_QueryCartProductTotalNum];
}


- (void)getShoppingCar{
    
    NSDictionary * dic1 = [Common getLoginInfo];
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    [dic  setObject:[NSNumber numberWithInteger:self.pageNO]     forKey:@"currentPage"];
    [dic  setObject:[NSNumber numberWithInteger:PageSize]       forKey:@"pageSize"];
    [dic setObject:dic1[@"userId"] forKey:@"userId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_ShoppingCarGoods withHttpType:@"POST" withTag:SX_SX_ShoppingCarList];
    
}

#pragma mark ---------- 返回
- (IBAction)backHandel:(id)sender {
    [self.navigationController  popViewControllerAnimated:YES];
}

#pragma mark ---------- 编辑
- (IBAction)settingHandel:(UIButton*)sender {
    sender.selected =!sender.selected;
   
    if (sender.selected==NO) {
        [sender setTitle:@"编辑" forState:UIControlStateNormal];
        _payView.hidden = NO;
        _deleteView.hidden = YES;
        _delete = NO;
        
        
        NSMutableDictionary  *dict=[NSMutableDictionary dictionary];
        [dict setObject:@"updateCartProductNum" forKey:@"method"];
        NSString * carId = @"";
        for (int i = 0; i<_goodsArray.count; i++) {
            NSArray * array = _goodsArray[i][@"goodsList"];
            for (int j = 0; j<array.count; j++) {
                NSString * idAndNumber = @"";
                if (i==_goodsArray.count-1 && j==array.count-1) {
                    idAndNumber = [NSString stringWithFormat:@"%@:%@",array[j][@"cartDetailId"],array[j][@"goodsCartNum"]];
                }else{
                    idAndNumber =  [NSString stringWithFormat:@"%@:%@,",array[j][@"cartDetailId"],array[j][@"goodsCartNum"]];
                }
                carId = [carId stringByAppendingString:idAndNumber];
            }
        }
        [dict setObject:carId forKey:@"cartDetailId"];
        
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dict withPath:SX_updateCartProductNumber withHttpType:@"POST" withTag:SX_UpdateCartProductPorperty];
    }else{
    [sender setTitle:@"完成" forState:UIControlStateNormal];
          _payView.hidden = YES;
         _deleteView.hidden = NO;
        _delete = YES;
    }
     [_listTableView reloadData];
}
#pragma mark ---------- 结算
- (IBAction)payHandel:(id)sender {

    if (![Common getLoginStatus]) {
        [self ShowLoginPage];
    }else{
               UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    SureIndentViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"SureIndent"];
    
    if (_choseArray.count==0) {
        [[CWHUDTips sharedInstance]  showTips:@"请选择商品"];
    }else{

        NSMutableArray * array = [NSMutableArray array];
        for (int i = 0;i<_goodsArray.count;i++) {
            NSMutableDictionary * dic = _goodsArray[i];
            NSMutableArray * list = [NSMutableArray array];
            for (NSIndexPath * path in _choseArray.allValues) {
                if (path.section == i) {
                    [list addObject:dic[@"goodsList"][path.row]];
                }
            }
            if(list.count>0){
                [dic setObject:list forKey:@"goodsList"];
                [array addObject:dic];
            }
        }
        page.goodsInfoArray = array;
        page.number = [NSString stringWithFormat:@"%ld",_choseArray.count];
        page.countMoney = [NSString stringWithFormat:@"%f",_totalMoney];
        page.payType = @"2";
        [self.navigationController   pushViewController:page animated:YES];
    }
    }
    
    
}
#pragma mark ---------- 编辑删除
- (IBAction)deleteHandel:(id)sender {
    NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
    NSString * carIds = @"";
    for (NSIndexPath * path in _choseArray.allValues) {
        NSDictionary  * dict = _goodsArray[path.section][@"goodsList"][path.row];
            NSString * carId = @"";
            if (path == [_choseArray.allValues lastObject]) {
                carId = [NSString stringWithFormat:@"%@",dict[@"cartDetailId"]];
            }else{
             carId = [NSString stringWithFormat:@"%@,",dict[@"cartDetailId"]];
            }
        carIds = [carIds stringByAppendingString:carId];
    }
    [dic setObject:carIds forKey:@"cartDetailId"];
    [dic setObject:@"deleteCartProductPorperty " forKey:@"method"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dic withPath:SX_deleteCartProductPorperty withHttpType:@"POST" withTag:SX_SX_deleteCartProductPorperty];
    
    
}
#pragma mark ---------- 隐藏修改款式View
- (IBAction)hideChangeView:(id)sender {
   
    [UIView animateWithDuration:0.5 animations:^{
        
        self.sureChangeButton.frame = flexibleFrame(CGRectMake(0, 524+567, 320, 44), NO);
        self.propertyView.frame = flexibleFrame(CGRectMake(0, 180+567, 320, 344), NO);
        self.changePropertyView.alpha = 0;
    } completion:^(BOOL finished) {
        self.changePropertyView.hidden = YES;
        _typeAndSize.text = [NSString stringWithFormat:@"已选：“%@”“%@”",_size,_type];
    }];
    
   
}

#pragma mark ---------- 确认修改款式View
- (IBAction)sureChange:(id)sender {

    [UIView animateWithDuration:0.5 animations:^{
        self.sureChangeButton.frame = flexibleFrame(CGRectMake(0, 524+567, 320, 44), NO);
        self.propertyView.frame = flexibleFrame(CGRectMake(0, 180+567, 320, 344), NO);
        self.changePropertyView.alpha = 0;
    } completion:^(BOOL finished) {
        self.changePropertyView.hidden = YES;

    }];
    NSMutableDictionary * dic = [_goodsArray[_changSection][@"goodsList"][_changIndex] mutableCopy];
    [dic setObject:[NSString stringWithFormat:@"颜色分类：%@；尺码：%@",_type,_size] forKey:@"mgooName"];
    [_goodsArray[_changSection][@"goodsList"] replaceObjectAtIndex:_changIndex withObject:dic];
    [_listTableView reloadData];
    
    
    NSMutableDictionary  *dict=[NSMutableDictionary dictionary];
    [dict setObject:@"updateCartProductPorperty" forKey:@"method"];
    [dict setObject:_mgspId forKey:@"mgspId"];
      [dict setObject:_goodsArray[_changSection][@"goodsList"][_changIndex][@"cartDetailId"] forKey:@"cartDetailId"];
    self.shareApi.delegate=self;
    [self.shareApi  requestOperationWithDic:dict withPath:SX_updateCartProductPorperty withHttpType:@"POST" withTag:SX_UpdateCartProductPorperty];
}


#pragma mark == 选择整个商家
- (void)choseSection:(UIButton *)sender{
    sender.selected = !sender.selected;
    UIButton * button = (UIButton *)[self.view viewWithTag:sender.tag-1];
    button.selected = sender.selected;
    
    NSArray * array = _goodsArray[sender.tag/100-1][@"goodsList"];
    
  
        for (int i = 0; i<array.count; i++) {

            ShoppingBagTableViewCell * cell = [_listTableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:i inSection:sender.tag/100-1]];
            
            if (sender.selected) {
                [_choseArray setObject:[NSIndexPath indexPathForRow:i inSection:sender.tag/100-1] forKey:[NSString stringWithFormat:@"%ld%d",sender.tag/100-1,i]];
                cell.choseDownButton.selected = YES;
                cell.choseButton.selected = YES;
            }else{
                [_choseArray removeObjectForKey:[NSString stringWithFormat:@"%ld%d",sender.tag/100-1,i]];
                cell.choseDownButton.selected = NO;
                cell.choseButton.selected = NO;
            }
        }
    
    [self countPrice];
}


#pragma mark === 进入商家
- (void)shopInfoHandel:(UIButton *)sender{

//    _goodsArray[sender.tag/100-1]
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    ShopViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"Shop"];
    page.storeId =  _goodsArray[sender.tag/100-1][@"mallStoreId"];
    [self.navigationController   pushViewController:page animated:YES];
    
}

- (void)countPrice{
    _totalMoney= 0;
    for (int i = 0; i<_choseArray.allKeys.count; i++) {
        NSIndexPath * indexP = _choseArray[_choseArray.allKeys[i]];
        NSDictionary * dic = _goodsArray[indexP.section][@"goodsList"][indexP.row];
         _totalMoney +=[dic[@"mgooPublishPrice"] floatValue]*[dic[@"goodsCartNum"]integerValue];
    }
    _totalPrice.text = [NSString stringWithFormat:@"￥%.2lf",_totalMoney];

    [_payButton setTitle:[NSString stringWithFormat:@"结算(%ld)",_choseArray.allKeys.count] forState:UIControlStateNormal];
    [_deleteButton setTitle:[NSString stringWithFormat:@"删除(%ld)",_choseArray.allKeys.count] forState:UIControlStateNormal];
}

#pragma mark -- UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _goodsArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 110*VerticalRatio();
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 35*VerticalRatio();
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSArray * array = _goodsArray[section][@"goodsList"];
    return array.count;
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    
    UIView * view = [[UIView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 0, 320, 35), NO)];
    view.backgroundColor = [UIColor whiteColor];
    
    UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = flexibleFrame(CGRectMake(12, 10, 19, 19), NO);
    [button setBackgroundImage:[UIImage imageNamed:@"shopping5"] forState:UIControlStateNormal];
    [button setBackgroundImage:[UIImage imageNamed:@"shopping4"] forState:UIControlStateSelected];
    button.tag = 100*(section+1);
    [view addSubview:button];
    
    UIButton * Button = [UIButton buttonWithType:UIButtonTypeCustom];
    Button.frame = flexibleFrame(CGRectMake(0, 0, 50 , 35), NO);
    Button.tag = 100*(section+1)+1;
    [view addSubview:Button];
    [Button addTarget:self action:@selector(choseSection:) forControlEvents:UIControlEventTouchUpInside];
    

    UIImageView * home = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(40, 9, 19, 17), YES)];
    home.image = [UIImage imageNamed:@"shopping15"];
    [view addSubview:home];
    
    UILabel * label =  [[UILabel alloc]initWithFrame:flexibleFrame(CGRectMake(65,0, 165, 35), NO)];
    label.textAlignment = NSTextAlignmentLeft;
    label.textColor = [UIColor colorWithWhite:0.196 alpha:1.000];
    label.font = [UIFont systemFontOfSize:15*VerticalTexeRatio()];
    label.text = _goodsArray[section][@"mallStoreName"];
    [view addSubview:label];
    
    
    CGSize  size = [label.text sizeWithFont:[UIFont systemFontOfSize:15*VerticalTexeRatio()]];
    if (size.width>165*VerticalRatio()) {
        size.width = 165*VerticalRatio();
    }
    
    UIImageView * backImage = [[UIImageView alloc]initWithFrame:flexibleFrame(CGRectMake(75+size.width,10, 8, 15), NO)];
    backImage.image = [UIImage imageNamed:@"shopping1"];
    [view addSubview:backImage];
    
    UIButton * infoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    infoButton.frame = flexibleFrame(CGRectMake(70,0, 250, 35), NO);
    infoButton.backgroundColor = [UIColor clearColor];
    infoButton.tag = 100*(section+1)+2;
    [view addSubview:infoButton];
    [infoButton addTarget:self action:@selector(shopInfoHandel:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    
    NSInteger count = 0;
    for (int i = 0; i<_choseArray.allKeys.count; i++) {
        NSString * key = _choseArray.allKeys[i];
        if ([[key substringToIndex:1] isEqualToString:[NSString stringWithFormat:@"%ld",section]]) {
            count ++;
        }
    }
    NSArray * array = _goodsArray[section][@"goodsList"];
    if (array.count == count) {
        button.selected = YES;
        Button.selected = YES;
    }
    
    return view;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    ShoppingBagTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify forIndexPath:indexPath];
    if (!cell) {
        cell = [[ShoppingBagTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentify];
    }else{
        
        for (UIView *view in cell.subviews) {
            if ([view isKindOfClass:[UILabel class]] ||[view isKindOfClass:[UIImageView class]]||[view isKindOfClass:[UIScrollView class]]||[view isKindOfClass:[UIButton class]]) {
                [view removeFromSuperview];
            }
        }
    }
    cell.selectionStyle=UITableViewCellSelectionStyleNone;
    
    
    
    
    NSString * image = _goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"appAdertImagUriName"];
    if (image.length>0) {
        [cell.goodsImage sd_setImageWithURL:[NSURL URLWithString:image]];
    }else{
        cell.goodsImage.image =[UIImage imageNamed:@"cloth1"];
    }
    cell.infoLabel.text = [NSString stringWithFormat:@"%@",_goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"mgooName"]];
    cell.infoLabel.frame = flexibleFrame(CGRectMake(130, 10, 172, 20), NO);
    cell.infoLabel.numberOfLines = 0;
    [cell.infoLabel sizeToFit];
    cell.neNumberLabel.text = [NSString stringWithFormat:@"%@",_goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"goodsCartNum"]];
    if (_delete == NO) {
        cell.infoLabel.hidden = NO;
        cell.priceLabel.hidden = NO;
        cell.numberLabel.hidden = NO;
        cell.editingView.hidden = YES;
        cell.moreButton.hidden = YES;
        cell.propertyLabel .frame = flexibleFrame(CGRectMake(130, 50, 172, 20), NO);
    }else{
        cell.propertyLabel .frame = flexibleFrame(CGRectMake(130, 65, 172, 20), NO);
        cell.infoLabel.hidden = YES;
        cell.priceLabel.hidden = YES;
        cell.numberLabel.hidden = YES;
        cell.editingView.hidden = NO;
        cell.moreButton.hidden = NO;
    }
    cell.propertyLabel.text = [NSString stringWithFormat:@"%@",_goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"mgseSpecifyDetailJson"]];
    [cell.propertyLabel sizeToFit];
    cell.numberLabel.text = [NSString stringWithFormat:@"x%@",_goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"goodsCartNum"]];
    
    NSString * str = [NSString stringWithFormat:@"￥%@",[Common stringFromData:_goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"mgooPublishPrice"]]];
    NSString * oldPrice = [NSString stringWithFormat:@"￥%@",[Common stringFromData:_goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"mgooPublishPrice"]]];
    
    NSMutableAttributedString * price = [[NSMutableAttributedString alloc]initWithString:[NSString stringWithFormat:@"%@     %@",str,oldPrice]];
    [price addAttribute:NSForegroundColorAttributeName value:[UIColor colorWithWhite:0.612 alpha:1.000] range:NSMakeRange(price.length-oldPrice.length, oldPrice.length)];
    [price addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13*VerticalTexeRatio()] range:NSMakeRange(price.length-oldPrice.length, oldPrice.length)];
    [price addAttribute:NSStrikethroughStyleAttributeName value:[NSNumber numberWithInteger:NSUnderlineStyleSingle] range:NSMakeRange(price.length-oldPrice.length, oldPrice.length)];
    [price addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16*VerticalTexeRatio()] range:NSMakeRange(0, str.length)];
    
    cell.priceLabel.attributedText = price ;
    

    
    cell.choseButton.selected = NO;
    cell.choseDownButton.selected = NO;
    
    for (int i = 0; i<_choseArray.allValues.count; i++) {
        NSIndexPath * path = _choseArray.allValues[i];
        if (path == indexPath) {
            cell.choseButton.selected = YES;
            cell.choseDownButton.selected = YES;
        }
    }
    
    
    
    
    cell.choseBlock = ^(NSString *str){
        if ([str isEqualToString:@"1"]) {
            
            [_choseArray setObject:[NSIndexPath indexPathForRow:indexPath.row inSection:indexPath.section] forKey:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row] ];
            
        }else{
            [_choseArray removeObjectForKey:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]];
            
        }
        
        
        NSInteger count = 0;
        for (int i = 0; i<_choseArray.allKeys.count; i++) {
            NSString * key = _choseArray.allKeys[i];
            if ([[key substringToIndex:1] isEqualToString:[NSString stringWithFormat:@"%ld",indexPath.section]]) {
                count ++;
            }
        }
        NSArray * array = _goodsArray[indexPath.section][@"goodsList"];
        if (array.count == count) {
            UIButton * button = (UIButton *)[self.view viewWithTag:100*(indexPath.section+1)+1] ;
            button.selected = YES;
            UIButton * Button = (UIButton *)[self.view viewWithTag:100*(indexPath.section+1)] ;
            Button.selected = YES;
        }else
        {
            UIButton * button = (UIButton *)[self.view viewWithTag:100*(indexPath.section+1)+1] ;
            button.selected = NO;
            UIButton * Button = (UIButton *)[self.view viewWithTag:100*(indexPath.section+1)] ;
            Button.selected = NO;
        }
        
        [self countPrice];
        
        
    };
    
    cell.addBlock = ^(NSString *str){
        _changIndex = indexPath.row;
        _changSection = indexPath.section;
        if ([str isEqualToString:@"1"]) {
            
            NSMutableDictionary * dic = [_goodsArray[indexPath.section][@"goodsList"][indexPath.row] mutableCopy];
            NSInteger number = [dic[@"goodsCartNum"] integerValue];
            number += 1;
            [dic setObject:[NSString stringWithFormat:@"%ld",number] forKey:@"goodsCartNum"];
            [_goodsArray[indexPath.section][@"goodsList"] replaceObjectAtIndex:indexPath.row withObject:dic];
            
            NSArray * array = _choseArray.allKeys;
            if ([array containsObject:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]]) {
                [self countPrice];
            }
            [_listTableView reloadData];
            
        }
    };
    
    cell.deleteBlock = ^(NSString *str){
        _changIndex = indexPath.row;
        _changSection = indexPath.section;
        if ([str isEqualToString:@"1"]) {
            NSMutableDictionary * dic = [_goodsArray[indexPath.section][@"goodsList"][indexPath.row] mutableCopy];
            NSInteger number = [dic[@"goodsCartNum"] integerValue];
            number -= 1;
            
            
            
            if (number<=1) {
                number = 1;
                [[CWHUDTips sharedInstance]  showTips:@"受不了了，不能再减少了哦"];
            }
            [dic setObject:[NSString stringWithFormat:@"%ld",number] forKey:@"goodsCartNum"];
            [_goodsArray[indexPath.section][@"goodsList"] replaceObjectAtIndex:indexPath.row withObject:dic];
            
            if (number>0){
                NSArray * array = _choseArray.allKeys;
                if ([array containsObject:[NSString stringWithFormat:@"%ld%ld",indexPath.section,indexPath.row]]) {
                    [self countPrice];
                    
                }
            }
            
            [_listTableView reloadData];
        }
    };
    
    
    cell.changeBlock = ^(NSString *str){
        _changIndex = indexPath.row;
        _changSection = indexPath.section;
        _typeAndSize.text = [NSString stringWithFormat:@"%@",_goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"mgooName"]];
        
        
        NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
        [dic setObject:@"queryGoodsUpProperty" forKey:@"method"];
        [dic setObject:_goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"mgooId"] forKey:@"mgooId"];
        [dic setObject:_goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"mgseSpecifyDetail"] forKey:@"mgseSpecifyDetail"];
        self.shareApi.delegate=self;
        [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGoodsUpProperty withHttpType:@"POST" withTag:SX_QueryGoodsUpProperty];
        
    };
    
    
    
    
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    UIStoryboard *secondStroyBoard=[UIStoryboard storyboardWithName:@"HomeStoryboard" bundle:nil];
    ShoppingProductDetailViewController *page = [secondStroyBoard instantiateViewControllerWithIdentifier:@"ShoppingProductDetail"];
    page.goodsId = [NSString stringWithFormat:@"x%@",_goodsArray[indexPath.section][@"goodsList"][indexPath.row][@"mgooId"]];
    [self.navigationController   pushViewController:page animated:YES];

}


#pragma   mark---- GetADBanner Request Delegate

-(void)fetchDatabaseFinished:(NSMutableDictionary *)database withTag:(NSInteger)tag{
    
    [_listTableView.header endRefreshing];
     if (tag==SX_SX_ShoppingCarList){
        if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
            
            [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
            
        }else  {
            dispatch_async(dispatch_get_main_queue(), ^{
                _totle = [database[@"totalResults"] integerValue];
                if (_totle > PageSize) {
                    __weak __typeof(self) weakSelf = self;
                    if (!self.listTableView.footer) {
                        // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
                        self.listTableView.footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
                            [weakSelf loadMoreData];
                        }];
                    }
                }
                if (self.pageNO == 1) {
                    [self.goodsArray removeAllObjects];
                }
                NSArray *arr = database[@"result"][@"pageRecord"];
                for (id entity in arr) {
                    [self.goodsArray addObject:entity];
                }
                
                
                _listTableView.dataSource = self;
                _listTableView.delegate = self;
                [_listTableView reloadData];
                
            });
        
          
            
        }
     }else if (tag == SX_QueryGoodsUpProperty){
         if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
             
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
             
         }else  {
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
             NSArray *arr = database[@"result"];
             if (arr.count < 1) {
                 return;
             }
             _perportyDic = database[@"result"][0];
             [_perportyOneArr removeAllObjects];
             _perportyOneArr = database[@"result"][0][@"specifyList"];

             _propertyPrice.text = [NSString stringWithFormat:@"￥%.2f",[database[@"result"][0][@"mgsePrice"]floatValue]];
             _propertyNumber.text = [NSString stringWithFormat:@"库存%@件",database[@"result"][0][@"mgspCurrentCount"]];
             
             
                          self.changePropertyView.hidden = NO;
                     [UIView animateWithDuration:0.5 animations:^{
                         self.sureChangeButton.frame = flexibleFrame(CGRectMake(0, 524, 320, 44), NO);
                         self.propertyView.frame = flexibleFrame(CGRectMake(0, 180, 320, 344), NO);
                         self.changePropertyView.alpha = 1;
             
                         NSString * image = _goodsArray[_changSection][@"goodsList"][_changIndex][@"appAdertImagUriName"];
                         if (image.length>0) {
                             [_propertyImage sd_setImageWithURL:[NSURL URLWithString:image]];
                         }else{
                             _propertyImage.image =[UIImage imageNamed:@"cloth1"];
                         }
             
                         _propertyPrice.text = [NSString stringWithFormat:@"￥%@",_goodsArray[_changSection][@"goodsList"][_changIndex][@"mgooPublishPrice"]];
                      
                     }];

             NSMutableArray * titles = [NSMutableArray array];
             NSMutableArray * textsArrays = [NSMutableArray array];
             
             for (int i=0; i<_perportyOneArr.count; i++) {
                 NSDictionary *perportyOneDic = _perportyOneArr[i];
                 
                 _perportyTwoArr = database[@"result"][0][@"specifyList"][i][@"specifyList"];
                 [titles addObject:perportyOneDic[@"mgspOoneName"]];
                 [textsArrays addObject:database[@"result"][0][@"specifyList"][i][@"specifyList"]];
             }
             
             AttributScroView * attScroView = [[AttributScroView alloc]initWithFrame:flexibleFrame(CGRectMake(0, 110, 320, 234), YES) titles:titles attributeTextArrays:textsArrays complect:^(NSArray *indexs) {
                 NSString * property = @"已选择：";
                 NSString * idStr ;
                 for (int i = 0; i<indexs.count; i++) {
                     NSArray * array = textsArrays[i];
                     NSString * text = [NSString stringWithFormat:@"“%@”",array[[indexs[i]integerValue]][@"mgspName"]];
                     property = [property stringByAppendingString:text];
                     if (i==0) {
                         idStr = [NSString stringWithFormat:@"%@",array[[indexs[i]integerValue]][@"mgsdId"]];
                     }else{
                         idStr = [idStr stringByAppendingString:[NSString stringWithFormat:@",%@",array[[indexs[i]integerValue]][@"mgsdId"]]];
                     }
                 }
                 _typeAndSize.text = property;
                 _typeAndSize.frame = flexibleFrame(CGRectMake(105, 72, 215, 20), YES);
                 [_typeAndSize sizeToFit];
                 NSMutableDictionary  *dic=[NSMutableDictionary dictionary];
                 [dic setObject:@"queryGoodsUpProperty" forKey:@"method"];
                 [dic setObject:_goodsArray[_changSection][@"goodsList"][_changIndex][@"mgooId"] forKey:@"mgooId"];
                 [dic setObject:idStr forKey:@"mgseSpecifyDetail"];
                 self.shareApi.delegate=self;
                 [self.shareApi  requestOperationWithDic:dic withPath:SX_queryGoodsUpProperty withHttpType:@"POST" withTag:SX_QueryGoodsUpPropertyDetail];
                 
             }];
             [_propertyView addSubview:attScroView];

         
         }
     
     }else if (tag == SX_QueryGoodsUpPropertyDetail){
         if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
             
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
             
         }else  {
             NSArray * array = database[@"result"];
             if (array.count == 0) {
                 _propertyPrice.text = [NSString stringWithFormat:@"￥%.2f",0.00];
                 _propertyNumber.text = [NSString stringWithFormat:@"库存%@件",@"0"];
             }else{
                 _mgspId = database[@"result"][0][@"mgspId"];
                 _mgspPrice = database[@"result"][0][@"mgsePrice"];
                 _propertyPrice.text = [NSString stringWithFormat:@"￥%.2f",[database[@"result"][0][@"mgsePrice"]floatValue]];
                 _propertyNumber.text = [NSString stringWithFormat:@"库存%@件",database[@"result"][0][@"mgspCurrentCount"]];
             }
         }
     }else if (tag == SX_UpdateCartProductNumber){
         if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
             
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
             
         }else  {
//             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
             
         }
     }else if (tag == SX_UpdateCartProductPorperty){
         if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
             
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
             
         }else  {
//             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
             
         }
     }else if (tag == SX_SX_deleteCartProductPorperty){
         if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
             
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
             
         }else  {
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
             [self addRefreshing];
             [self getBagNumber];
             [_deleteButton setTitle:@"删除(0)" forState:UIControlStateNormal];
             [_choseArray removeAllObjects];
             
         }
     }else if (tag == SX_QueryCartProductTotalNum){
         if (  [[database valueForKey:@"type"] integerValue]!=1 ) {
             
             [[CWHUDTips sharedInstance]  showTips:[database valueForKey:@"msg"]  withStatus:1 dismissAfter:1.5];
             
         }else  {
             [_headTitel setTitle:[NSString stringWithFormat:@"购物车(%@)", database[@"result"]] forState:UIControlStateNormal] ;
         }
         
     }

}
-(void)fetchDatabaseFailed:(NSError *)error message:(NSString *)message{
    
    //
    [self dismissWaitDialog];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
